import { defineStore } from 'pinia';

export default defineStore('landing', () => {
  const queryData = ref<AnyObject>({});
  const pageId = ref<string>('');
  const landingPageId = ref<string>('');
  const landingPageData = ref<AdLandingPageVO>();
  const isShowPopup = ref(false);
  const toSpec = ref(false);
  const getLandingPageId = async () => {
    if (landingPageId.value) return;
    const response = await $api.getTjAdLandingpage({ id: pageId.value });
    switch (response.__error) {
      case undefined:
        landingPageId.value = response.data.ad_landing_page_id;
        break;
    }
  };
  const getLandingPage = async () => {
    const response = await $api.getAdLandingpage({
      landing_page_id: landingPageId.value,
      summary: true
    });
    switch (response.__error) {
      case undefined:
        landingPageData.value = response.data;
        refluxIndex.value = -1;
        break;
    }
  };

  const refluxIndex = ref(-1);
  const refluxList = computed(() => {
    if (!landingPageData.value) return [];
    const list: {
      amount: number;
      type: LandingPageDiscountType;
      noPopup?: boolean;
      id?: string;
    }[] = [];
    let lastReturn:
      | {
          amount: number;
          type: LandingPageDiscountType;
          noPopup?: boolean;
          id?: string;
        }
      | undefined;
    if (landingPageData.value.subsidy_setting?.switch_flag) {
      const amount = landingPageData.value.subsidy_setting.amount;
      list.push({ amount, type: 'LANDING_PAGE_SUBSIDY' });
    } else {
      list.push({ amount: 0, type: 'NONE' });
    }
    if (landingPageData.value.retrieve_setting?.switch_flag) {
      const amount = landingPageData.value.retrieve_setting.amount;
      list.push({ amount, type: 'LANDING_PAGE_RETRIEVE' });
      list.push({ amount, type: 'LANDING_PAGE_RETRIEVE', noPopup: true }); // 返回时回流，点击关闭弹窗时跳过这个
      if (landingPageData.value.retrieve_setting.secondary_switch_flag) {
        const amount =
          landingPageData.value.retrieve_setting.secondary_retention_amount;
        list.push({ amount, type: 'LANDING_PAGE_SECONDARY_RETRIEVE' });
        list.push({
          amount,
          type: 'LANDING_PAGE_SECONDARY_RETRIEVE',
          noPopup: true
        }); // 返回时回流，点击关闭弹窗时跳过这个
      }
    }
    if (landingPageData.value.marketing_setting?.switch_flag) {
      const amount = landingPageData.value.marketing_setting.amount;
      list.push({ amount, type: 'MARKETING_PAGE_DISCOUNT' });
    }
    if (landingPageData.value.multilevel_reflux_setting?.switch_flag) {
      const refluxList =
        landingPageData.value.multilevel_reflux_setting
          .multilevel_reflux_style_type_list;
      for (let i = 0; i < refluxList.length; i += 1) {
        const item = refluxList[i];
        switch (item.style_type) {
          case 'LUCKY_REDPACKET':
            list.push({
              amount: item.amount,
              type: 'MULTILEVEL_REFLUX_LUCKY_REDPACKET',
              id: item.multilevel_reflux_setting_id
            });
            lastReturn = {
              amount: item.amount,
              type: 'MULTILEVEL_REFLUX_LUCKY_REDPACKET',
              id: item.multilevel_reflux_setting_id,
              noPopup: true
            };
            break;
          case 'FRIEND_REDPACKET':
            list.push({
              amount: item.amount,
              type: 'MULTILEVEL_REFLUX_FRIEND_REDPACKET',
              id: item.multilevel_reflux_setting_id
            });
            lastReturn = {
              amount: item.amount,
              type: 'MULTILEVEL_REFLUX_FRIEND_REDPACKET',
              id: item.multilevel_reflux_setting_id,
              noPopup: true
            };
            break;
        }
      }
    }
    if (lastReturn) list.push(lastReturn);
    return list;
  });
  const refluxCurrent = computed(() => {
    if (!landingPageData.value) return undefined;
    return refluxList.value[refluxIndex.value];
  });
  const discount = computed(() => {
    return {
      amount: refluxCurrent.value?.amount ?? 0,
      type: refluxCurrent.value?.type ?? 'NONE',
      id: refluxCurrent.value?.id
    };
  });
  const dynamicContent = computed<LandingDynamicContent | undefined>(() => {
    try {
      if (!landingPageData.value?.dynamic_content) return undefined;
      return JSON.parse(landingPageData.value.dynamic_content);
    } catch {
      return undefined;
    }
  });
  const components = computed(() => {
    if (!dynamicContent.value) return undefined;
    const components = dynamicContent.value.component_content || [];
    const list: typeof components = [];
    let carousel: LandingPageCarouselItem | undefined;
    let goods: LandingPageGoodsItem | undefined;
    let buy: LandingPageBuyItem | undefined;
    for (let i = 0; i < components.length; i += 1) {
      const component = components[i];
      switch (component.el) {
        case 'Carousel':
          carousel = component;
          break;
        case 'Goods':
          goods = component;
          list.push(component);
          break;
        case 'Buy':
          buy = component;
          break;
        default:
          list.push(component);
      }
    }
    return { list, carousel, goods, buy };
  });

  const product = ref<SpuVO>();
  const getProductDetails = async () => {
    if (!landingPageData.value?.spu_id) return;
    if (product.value) return;
    const response = await $api.getSearchIdDetail(landingPageData.value.spu_id);
    switch (response.__error) {
      case undefined:
        product.value = response.data;
        product.value.handy_sku_list = product.value.handy_sku_list
          ? product.value.handy_sku_list.filter((item) => item.inventory)
          : [];
        break;
    }
  };

  const merchant = ref<MerchantVO>();
  const merchantContact = computed(() => {
    if (merchant.value?.customer_service_status !== 'ENABLED') return undefined;
    const tntInstId = merchant.value?.customer_service_setting?.tenant_id;
    const scene = merchant.value?.customer_service_setting?.chat_window_id;
    if (!tntInstId || !scene) return undefined;
    return { tntInstId, scene };
  });
  const getMerchant = async () => {
    if (!landingPageData.value?.merchant_id) return;
    const response = await $api.getMerchantId(
      landingPageData.value.merchant_id
    );
    switch (response.__error) {
      case undefined:
        merchant.value = response.data;
        break;
    }
  };
  const recordMerchant = async () => {
    if (!landingPageData.value?.merchant_id) return;
    $api.postMerchantView(
      { merchant_id: landingPageData.value.merchant_id },
      { notifyApiError: false }
    );
  };

  const navigatedMerchantIndex = ref(false);

  const loadData = async () => {
    if (!landingPageId.value) await getLandingPageId();
    if (!landingPageData.value) await getLandingPage();
    const list: Promise<void>[] = [];
    if (!product.value) list.push(getProductDetails());
    if (!merchant.value) {
      list.push(getMerchant(), recordMerchant());
    }
    if (list.length) await Promise.all(list);
  };
  const initData = () => {
    landingPageData.value = undefined;
    product.value = undefined;
    merchant.value = undefined;
    refluxIndex.value = -1;
  };

  return {
    queryData,
    pageId,
    landingPageId,
    landingPageData,
    dynamicContent,
    refluxIndex,
    refluxList,
    refluxCurrent,
    toSpec,
    isShowPopup,
    discount,
    product,
    components,
    merchant,
    merchantContact,
    navigatedMerchantIndex,
    initData,
    loadData
  };
});
